<?php

namespace app\yy\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\yy\model\Images as ImgModel;
use app\yy\model\Website as WebModel;
use think\db\Where;

class Images extends Admin
{
    public $status = [
        '0' => '未启用:default',
        '1' => '已成功:success',
        '2' => '迁移中:primary',
        '3' => '迁移失败:danger',
        '4' => '待处理:info'
    ];

    public $image_status = [
        '0' => '停止:default',
        '1' => '待加载:info',
        '2' => '加载中:primary',
        '3' => '加载失败:danger',
        '4' => '加载成功:success'
    ];

    public function index()
    {
        // 根据网站进行图片分组
        $map = $this->getMap();
        $data_list = WebModel::where($map)->where('status',4)->order('id desc')->paginate();
//         $data_list = WebModel::where($map)->order('id desc')->paginate();
        $web = WebModel::column('domain','id');
        $website_ids = array_column($data_list->toArray()['data'],'id');
        if ($website_ids){
            // 图片迁移状态
            $images = ImgModel::field(['status','website_id',"count(*) as total"])->where('website_id','in',$website_ids)->group('website_id,status')->select();
            $statistics = [];
            foreach ($images as $image){
                $statistics[$image['website_id']][$image['status']] = $image['total'];
            }
            // 图片预加载
            $images = ImgModel::field(['image_status','website_id',"count(*) as total"])->where('website_id','in',$website_ids)->where('rank',0)->group('website_id,image_status')->select();
            $image_statistics = [];
            foreach ($images as $image){
                $image_statistics[$image['website_id']][$image['image_status']] = $image['total'];
            }
            foreach ($data_list as &$data){
                $data->await = $statistics[$data->id][0] ?? 0;
                $data->success = $statistics[$data->id][1] ?? 0;
                $data->process = $statistics[$data->id][2] ?? 0;
                $data->lose = $statistics[$data->id][3] ?? 0;
                $data->img_await = $image_statistics[$data->id][0] ?? 0;
                $data->img_success = $image_statistics[$data->id][1] ?? 0;
                $data->img_process = $image_statistics[$data->id][2] ?? 0;
                $data->img_lose = $image_statistics[$data->id][3] ?? 0;
            }
        }
        return ZBuilder::make('table')
            ->setPageTitle('图片统计') // 设置页面标题
            ->setSearchArea([
                ['select', 'id', '迁移网站', '','',$web],
                ['text', 'domain', '迁移网站', 'like'],
                ['select', 'image_status', '预加载状态', '', '', $this->image_status],
            ])
            ->addColumns([ // 批量添加列
                ['id', '网站ID'],
                ['brand', 'YY-品牌名'],
                ['domain', '迁移网站'],
                ['success', 'oss-成功'],
                ['await', 'oss-待处理'],
                ['process', 'oss-处理中'],
                ['lose', 'oss-失败'],
                ['image_status', '预加载状态','status','',$this->image_status],
                ['img_success', '预加载-成功'],
                ['img_await', '预加载-待处理'],
                ['img_process', '预加载-处理中'],
                ['img_lose', '预加载-失败'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('custom', [
                'title' => '详情',
                'class' => 'btn btn-primary',
                'icon'  => 'fa fa-fw fa-folder-open',
                'href'  => url('detail', ['website_id' => '__id__']),
            ])
            ->addRightButton('preload', [
                'title' => '图片预加载',
                'class' => 'btn btn-success',
                'icon'  => 'fa fa-fw fa-image',
                'href'  => url('preload', ['website_id' => '__id__']),
            ])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                '_checkbox' => 10,
                'id' => 15,
                'brand' => 30,
                'domain' => 50,
                'success' => 28,
                'await' => 28,
                'process' => 28,
                'lose' => 28,
                'image_status' => 30,
                'img_success' => 28,
                'img_await' => 28,
                'img_process' => 28,
                'img_lose' => 28,
                'right_button' => 30,
            ])
            ->fetch(); // 渲染页面
    }

    /**
     * 图片预加载
     * @param $website_id
     * @return void
     */
    public function preload($website_id='')
    {
        // 添加预加载状态
        if (WebModel::where('id',$website_id)->update(['image_status'=>1])){
            ImgModel::where('website_id',$website_id)->update(['image_status'=>0]);
            $this->success('开始生成缩略图');
        }else{
            $this->error('预加载打开失败');
        }
    }

    public function detail($website_id='')
    {
        // 获取查询条件
        $map = $this->getMap();
        $data_list = ImgModel::where($map)->where('website_id',$website_id)->order('id desc')->paginate();
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('图片列表') // 设置页面标题
            ->setTableName('images') // 设置数据表名
            ->setSearchArea([
                ['select', 'status', '状态', '', '', $this->status],
                ['text', 'sku', '商品sku', 'like'],
                ['text', 'yy_image', 'YY图片', 'like']
            ])
            ->addColumns([ // 批量添加列
                ['id', 'ID'],
                ['sku', '商品SKU'],
                ['yy_image', '原图片'],
                ['oss_image', 'OSS图片'],
                ['status', '状态', 'status', '', $this->status],
                ['remark', '备注'],
//                ['add_time', '添加时间'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('disable',['title' => '重新处理']) // 批量添加顶部按钮
            ->replaceRightButton(['status' => 1], '','disable')
            ->addRightButton('disable',['title' => '重新处理']) // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                '_checkbox' => 10,
                'id' => 15,
                'web_dir' => 50,
                'sku' => 30,
                'image' => 50,
                'local_path' => 20,
                'status' => 25,
                'add_time' => 20,
                'right_button' => 30,
            ])
            ->fetch(); // 渲染页面
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data['img_dir']){
                $this->error('YY站点 必填');
            }
            if (!$data['atta_id']){
                $this->error('YY文件 必填');
            }
            if (!$data['domain']){
                $this->error('迁移网站 必填');
            }
            if (!$data['server_id']){
                $this->error('服务器 必选');
            }
            if (!$data['db_hostname']){
                $this->error('数据库地址 必填');
            }
            if (!$data['db_database']){
                $this->error('数据库名 必填');
            }
            if (!$data['db_username']){
                $this->error('数据库用户名 必填');
            }
            if (!$data['db_password']){
                $this->error('数据库密码 必填');
            }
            if (WebModel::create($data)) {
                $this->success('新增成功', url('index'));
            } else {
                $this->error('新增失败');
            }
        }
        $server = \app\yy\model\Server::column('name','id');
        return ZBuilder::make('form')
            ->setPageTitle('添加')
            ->addSelect('type', '网站类型', '', $this->type,0)
            ->addSelect('server_id', '网站所属服务器', '', $server,0)
            ->addText('img_dir','YY站点')
            ->addFile('atta_id','YY文件','','','','xlsx')
            ->addText('domain','迁移网站','二级域名【www.baidu.com】，与网站的目录需保持一致')
            ->addText('db_hostname','数据库地址')
            ->addText('db_database','数据库名')
            ->addText('db_username','数据库用户名')
            ->addText('db_password','数据库密码')
            ->fetch();
    }

}